<?php
/*
 * @Author: 李明
 * @Date: 2021-09-25 10:30:04
 * @LastEditTime: 2022-01-17 15:12:52
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/app/login/LoginAppController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\app\login;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\Jwt;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Message\MessageController;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginAppController extends Controller
{
    public function ChangePassword(Request $request)
    {
        try {
            $all = $request->all();
            $passwordMd5 = CommonFun::md5($all['password']);
            $phone_num = $all['phone_num'];
            $code = $all['code'];
            $account = $all['account'] ?? '';
        } catch (\Throwable $th) {
            return LMReturn::Error("传参错误");
        }

        try {

            $codeMsg = Redis::get($phone_num) ?? '';
            if ($codeMsg == $code) {
                if ($account == '') {
                    $user_list = User::where('contact_manner', $phone_num)->get();
                    $user_count = count($user_list);
                    if ($user_count == 0) {
                        return LMReturn::Error('不存在该手机号', 'LACCP3');
                    } elseif ($user_count > 1) {
                        return LMReturn::Error('无法根据手机号获取用户，请填写账号', 'LACCP2');
                    } else {
                        $user = $user_list->first();
                    }
                } else {
                    $user_list = User::where('account', $account)->get();
                    if (count($user_list) == 0) {
                        return LMReturn::Error('不存在该账号', 'LACCP6');
                    }
                    $user = $user_list[0];
                    if ($user->contact_manner != $phone_num) {
                        return LMReturn::Error('手机号和账号不匹配，请检查', 'LACCP1');
                    }
                }
                $old_password = $user->password;
            } else {
                return LMReturn::Error("验证码错误");
            }

            if ($old_password == $passwordMd5) {
                return LMReturn::Error("新密码不能和旧密码一致", 'LACCP4');
            } else {
                $user->password = $passwordMd5;
                $user->is_update_pwd = 1;
                $user->save();
                return LMReturn::Success($user, '密码修改成功');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error("密码修改失败", 'LACCP5');
        }
    }
    /**
     * @description: 登录接口
     * @param {Request} $request
     * @return {*}
     */
    public function UserLogin(Request $request)
    {
        //接收前段传递过来的信息
        try {
            $all = $request->all();
            $type = $all['type']; // 登录方式 1密码，2验证码
            $channel = Request()->header('channel') ?? '3'; //3 iOS  4 安卓
            if ($type == '1') {
                $account = $all['account'];
                $password = $all['password'];
            } elseif ($type == '2') {
                $phone_num = $all['phone_num'];
                $code = $all['code'];
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现错误,错误码LAC001');
        }
        // 处理参数
        try {
            if ($type == '1') {
                $user_list = User::where('account', $account)->get();
            } elseif ($type == '2') {
                $user_list = User::where('contact_manner', $phone_num)->get();
            }
            //根据传递过来的手机号信息进行数据库查询
            $user_count = count($user_list);
            if ($user_count == 0) {
                return LMReturn::Error('输入的账号不存在，请确认之后再进行登录,错误码LAC002');
            } elseif ($user_count > 1) {
                return LMReturn::Error('您名下存在多个账号，请联系您的客户经理获取账号,错误码LAC003');
            } elseif ($user_count == 1) {
                $user = $user_list->first();
                if ($type == 1) { // 密码登录
                    $login_data = $this->PasswordLogin(CommonFun::md5($password), $user, $channel);
                    if ($login_data) {
                        return LMReturn::Success($login_data, '登录成功');
                    } else {
                        return LMReturn::Error('密码错误');
                    }
                } elseif ($type == 2) { // 验证码登录
                    $login_data = $this->CodeLogin($code, $user, $channel);
                    if ($login_data) {
                        return LMReturn::Success($login_data, '登录成功');
                    } else {
                        return LMReturn::Error('验证码错误');
                    }
                } else {
                    return LMReturn::Error('请选择登录方式');
                }
            } else {
                return LMReturn::Error('您的账号存在异常，请联系管理员或者更换登录方式,错误码LAC004');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('登录失败,错误码LAC005');
        }
    }
    /**
     * @description: 密码登录方法
     * @param {*} $password
     * @param {*} $user
     * @param {*} $channel  3 iOS  4安卓
     * @return {*}
     */
    public function PasswordLogin($password, $user, $channel = 3)
    {
        if ($password == $user->password) {
            return $this->LoginData($user, $channel);
        } else {
            return false;
        }
    }
    /**
     * @description: 验证码登录
     * @param {*} $code
     * @param {*} $user
     * @param {*} $channel  3 iOS  4安卓
     * @return {*}
     */
    public function CodeLogin($code, $user, $channel = 3)
    {
        $codeMsg = Redis::get($user->contact_manner);
        if ($codeMsg == $code) {
            return $this->LoginData($user, $channel);
        } else {
            return false;
        }
    }
    /**
     * @description: 登录数据
     * @param {*} $user
     * @param {*} $channel  3 iOS  4安卓
     * @return {*}
     */
    public function LoginData($user, $channel = 3)
    {
        $user_id = $user->id;
        $payload = [
            "iat" => time(),
            "user_id" => $user_id
        ];
        $token = Jwt::getToken($payload);
        $keyToken_user = CommonFun::TokenKeyCreate($user_id, $channel);
        Redis::setex("USER_TOKEN_" . $user_id, $this->tokenValidityLongTime(), $token);
        $user_icon = $user->icon;
        if ($user_icon == Null || $user_icon == '') {
            $user_icon = "http://as.1024xxkj.com/image_hx/20211224/bdca19a1f2fbe585a64f788b04e57a8c.jpg";
        }
        if ($user->xcx_open_id == null) {
            $is_xcx = 0;
        } else {
            $is_xcx = 1;
        }
        $user_data = [];
        $user_dic = json_decode($user, true);
        foreach ($user_dic as $key=>$value) {
            if ($value == null) {
                $user_data[$key] = '';
            } else {
                $user_data[$key] = $value;
            }
        }
        $login_data = [
            'token' => $token,
            "user_icon" => $user_icon,
            "user_name" => $user->name,
            "user_data"=>$user_data,
            "is_xcx" => $is_xcx,
            "update_status"=> $user->is_update_pwd,
            "unionid"=>$user->unionid ?? 2
        ];
        return $login_data;
    }
}
